import os,requests
import concurrent.futures
from qcloud_cos import CosConfig, CosS3Client

# 配置 COS SDK
secret_id = "AKIDYy95mGWXIo69wTs3yd5KK4auzoOjpfGc"
secret_key = "81f4FBtMbbLq7AELNDznU0LSL1SecNs9"
region = "ap-hongkong"
bucket = "hcecpod-1343049753"

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)



def get_existing_files(cos_folder):
    """ 获取 COS 目录下已有的所有文件 """
    existing_files = set()
    continuation_token = None  # COS 不支持 `ContinuationToken`，使用 `Marker` 替代

    while True:
        if continuation_token:
            response = client.list_objects(Bucket=bucket, Prefix=cos_folder, Marker=continuation_token)
        else:
            response = client.list_objects(Bucket=bucket, Prefix=cos_folder)

        if 'Contents' in response:
            for item in response['Contents']:
                existing_files.add(item['Key'])  # 存储文件路径

        # 判断是否还有更多数据
        if 'NextMarker' in response:
            continuation_token = response['NextMarker']
        else:
            break

    print(f"📌 已获取 COS 目录下 {len(existing_files)} 个文件")
    return existing_files

def download_image(filename, existing_files,local_folder):
    pic_name = filename.split('/')[1]

    if pic_name in existing_files:
        # print(f"⚠️ 文件已存在，跳过: {pic_name}")
        return

    url="https://hcecpod-1343049753.cos.ap-hongkong.myqcloud.com/"+filename
    save_path=os.path.join(local_folder,pic_name)
    
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        with open(save_path, 'wb') as f:
            f.write(response.content)
        print(f"[成功] 下载 {pic_name}")
    except requests.exceptions.RequestException as e:
        print(f"[失败] 下载 {pic_name} 错误: {e}")

def main():
    list_file=['draw','pattern','model','pingpu','choose','multipack']
    for file_name in list_file:
        print("现在备份的文件夹是：",file_name)
        cos_folder = file_name+"/"
        cos_files = get_existing_files(cos_folder)

        
        local_folder = "E:/腾讯云COS/hcecpod-1343049753/"+file_name
        existing_files = [f for f in os.listdir(local_folder) if os.path.isfile(os.path.join(local_folder, f))]
        print(print(f"📌 已获取 本地 目录下 {len(existing_files)} 个文件"))

        # 3️⃣ 多线程并行上传
        with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
            executor.map(lambda f: download_image(f, existing_files,local_folder), cos_files)

if __name__ == "__main__":
    main()